define(['jquery'], () => {
    class Header {
        constructor() {
            // header的内容是通过load方法异步加载的，所以要load成功的回调里才能反问道header里的DOM元素
            // 把异步代码封装成promise
            // 这样的好处是：把模块的核心逻辑放在constructor里而不是loadHTML里，loadHTML的逻辑共更单纯，易于维护
            this.loadHTML().then(() => {
                this.search()
                this.calcCartCount()
            })
        }
        loadHTML() {
            return new Promise(resolve => {
                $('header').load('/html/modules/header.html', () => {
                    resolve()
                })
            })
        }
        search() {
            $('#input_search').on('keyup', function () {
                console.log($(this).val())
            })
        }
        calcCartCount() {
            let cart = localStorage.getItem('cart')
            let count = 0
            if (cart) {
                cart = JSON.parse(cart)
                count = cart.reduce((sum, shop) => {
                    sum += shop.count
                    return sum
                }, 0)
            }
            $('#shopnum,#cart span').html(count)
        }
    }
    return new Header()
});